#include<linux/module.h>
#include<linux/fs.h>
#include<linux/init.h>
#include<linux/cdev.h>
#include<linux/slab.h>
#include<linux/uaccess.h>

#define GLOBALMEM_SIZE 0x1000
#define MEM_CLEAR 0x1
#define GLOBALMEM_MAJOR 230

static int globalmem_major = GLOBALMEM_MAJOR;
module_param(globalmem_major, int, S_IRUGO);

struct globalmem_dev{
    struct cdev cdev;
    unsigned char mem[GLOBALMEM_SIZE]; //内核中的一部分内存
    struct mutex mutex;
}; // 不一定放在一个结构中

struct globalmem_dev *globalmem_devp;


static int globalmem_open(struct inode *inode, struct file *filp){
    printk(KERN_INFO "into open\n");
    filp->private_data = globalmem_devp;
    return 0;
}

static int globalmem_release(struct inode *inode, struct file *filp){
    return 0;
}

// ppos是文件相对于文件开头的偏移
static ssize_t globalmem_read(struct file *filp, char __user *buf, size_t size, loff_t *ppos){
    unsigned long p = *ppos;
    unsigned int count = size;
    int ret = 0;
    struct globalmem_dev *dev = filp->private_data;
    // 文件偏移大于文件大小，读完了，返回EOF
    if(p >= GLOBALMEM_SIZE){
        return 0;
    }
    // 读的大小大于剩余文件大小，把剩余文件读完
    if(count > GLOBALMEM_SIZE - p){
        count = GLOBALMEM_SIZE - p;
    }

    mutex_lock(&dev->mutex);
    // 把内核数据拷贝到用户空间buf地址
    if(copy_to_user(buf, dev->mem + p, count)){
        ret = -EFAULT;
    } else {
        *ppos += count;
        ret = count;
        printk(KERN_INFO "read %u byte(s) from %lu\n", count, p);
    }
    mutex_unlock(&dev->mutex);
    return ret;
}

static ssize_t globalmem_write(struct file *filp, const char __user *buf, size_t size, loff_t *ppos){
    unsigned long p = *ppos;
    unsigned int count = size;
    int ret = 0;
    struct globalmem_dev *dev = filp->private_data;
    
    if(p >= GLOBALMEM_SIZE) return 0;

    if(count > GLOBALMEM_SIZE - p){
        count = GLOBALMEM_SIZE - p;
    }

    mutex_lock(&dev->mutex);
    if(copy_from_user(dev->mem + p, buf, count)){
        return -EFAULT;
    } else {
        *ppos += count;
        ret = count;

        printk(KERN_INFO "written %u byte(s) from %lu\n", count, p);
    }

    mutex_unlock(&dev->mutex);
    return ret;
}

static loff_t globalmem_llseek(struct file *filp, loff_t offset, int orig){
    loff_t ret = 0;
    switch(orig){
    case 0:
        if(offset < 0){
            ret = -EINVAL;
            break;
        }
        if((unsigned int)offset > GLOBALMEM_SIZE){
            ret = -EINVAL;
            break;
        }
        filp->f_pos = (unsigned int)offset;
        ret = filp->f_pos;
        break;
    case 1:
        if((filp->f_pos + offset) > GLOBALMEM_SIZE){
            ret = -EINVAL;
            break;
        }
        if((filp->f_pos + offset) < 0){
            ret = -EINVAL;
            break;
        }
        filp->f_pos += offset;
        ret =filp->f_pos;
        break;
    default:
        ret = -EINVAL;
        break;
    }
    return ret;
}

static long globalmem_ioctl(struct file *filp, unsigned int cmd, unsigned long arg){
    struct globalmem_dev *dev = filp->private_data;
    switch(cmd){
    case MEM_CLEAR:
        mutex_lock(&dev->mutex);
        memset(dev->mem, 0, GLOBALMEM_SIZE);
        mutex_unlock(&dev->mutex);

        printk(KERN_INFO "globalmem is set to  zero\n");
        break;
    default:
        return -EINVAL;
    }
    return 0;
}


static const struct file_operations globalmem_fops = {
    .owner = THIS_MODULE,
    .llseek = globalmem_llseek,
    .read = globalmem_read,
    .write = globalmem_write,
    .unlocked_ioctl = globalmem_ioctl,
    .open = globalmem_open,
    .release = globalmem_release,
};


// 完成cdev的初始化和添加
static void globalmem_setup_cdev(struct globalmem_dev *dev, int index){
    int err, devno = MKDEV(globalmem_major, index);
    // MKDEV:根据设备文件的major，minor号找到设备在设备表中的位置， index作为minor
    // 系统设备在`/proc/devices`中，格式为(设备编号，设备类型名)

    cdev_init(&dev->cdev, &globalmem_fops);
    dev->cdev.owner = THIS_MODULE;
    err = cdev_add(&dev->cdev, devno, 1);
    // `cdev_add`将设备注册到kernel，
    if(err){
        printk(KERN_NOTICE "Error %d adding globalmem%d\n", err, index);
    }
}


static int __init globalmem_init(void){
    int ret;
    dev_t devno = MKDEV(globalmem_major, 0);
    // `MKDEV`在此处直接确定了一个设备号
    if(globalmem_major){
        ret = register_chrdev_region(devno, 1, "globalmem");
        // 如果事先定义设备编号，就直接申请这个设备编号
    } else {
        ret = alloc_chrdev_region(&devno, 0, 1, "globalmem");
        // 如果实现没有定义设备编号，动态分配设备编号(ps.一些设备编号是静态分配给普通设备的)
        globalmem_major = MAJOR(devno);
    }   
    // 申请事先定义的设备编号出错，module加载失败
    if(ret < 0){
        return ret;
    }
    
    
    // 申请globalmem_dev结构体内存并置为0
    globalmem_devp = kzalloc(sizeof(struct globalmem_dev), GFP_KERNEL);
    if(!globalmem_devp){
        ret = -ENOMEM;
        goto fail_malloc;
    }

    mutex_init(&globalmem_devp->mutex);
    globalmem_setup_cdev(globalmem_devp, 0);
    return 0;

    fail_malloc:
    unregister_chrdev_region(devno, 1);
    return ret;
}

static void __exit globalmem_exit(void){
    cdev_del(&globalmem_devp->cdev);
    kfree(globalmem_devp->mem);
    unregister_chrdev_region(MKDEV(globalmem_major, 0), 1);
}

module_init(globalmem_init);
module_exit(globalmem_exit);


MODULE_AUTHOR("shang chao");
MODULE_LICENSE("GPL v2");

